<?php


function get_backup_settings($key)
{
    global $TABLE_PREFIX;
    
    $curr_conf_query = do_sqlquery("SELECT `value` FROM `{$TABLE_PREFIX}settings` WHERE `key` = '".$key."'", true);
    $curr_conf = @mysql_fetch_assoc($curr_conf_query);
    
    return $curr_conf["value"];
}


##get table contents
function get_data($table) {
     //global $conn;
     $content="\n--\n-- Data for $table\n--\n";
     $result = mysql_query("SELECT * FROM $table");
     while($row = mysql_fetch_row($result)) {
         $insert = "\nINSERT INTO $table VALUES (";
         for($j=0; $j<mysql_num_fields($result);$j++) {
            if(!isset($row[$j])) $insert .= "NULL,";
            else if($row[$j] != "") $insert .= "'".addslashes($row[$j])."',";
            else $insert .= "'',";
         }
         $insert = ereg_replace(",$","",$insert);
         $insert .= ");";
         $content .= $insert;
     }
     return $content;
}

################################
##get table defination
function get_def($table, $drop_table) {
   // global $conn;
    $def = "\n--\n-- Structure for $table\n--\n\n";
    if ($drop_table=='true')
       $def .= "DROP TABLE IF EXISTS $table;\n";
    $def .= "CREATE TABLE $table (\n";
    $result = mysql_query("SHOW FIELDS FROM $table") or die("Table does not exists");
    while($row = mysql_fetch_array($result)) {
        $def .= "    `$row[Field]` $row[Type]";
        if ($row["Default"] != "") $def .= " DEFAULT '$row[Default]'";
        if ($row["Null"] != "YES") $def .= " NOT NULL";
        if ($row[Extra] != "") $def .= " $row[Extra]";
            $def .= ",\n";
     }
     $def = ereg_replace(",\n$","", $def);
     $result = mysql_query("SHOW KEYS FROM $table");
     while($row = mysql_fetch_array($result)) {
          $kname=($row[Key_name] != "PRIMARY"?"`".$row[Key_name]."`":$row[Key_name]);
          if(($kname != "PRIMARY") && ($row[Non_unique] == 0)) $kname="UNIQUE|$kname";
          if ($row[Index_type]=="FULLTEXT") $kname="FULLTEXT|$kname";
          if(!isset($index[$kname])) $index[$kname] = array();
          $index[$kname][] = "`".$row[Column_name]."`".(isset($row[Sub_part])?" (".$row[Sub_part].")":"");
     }
     while(list($x, $columns) = @each($index)) {
          $def .= ",\n";
          if($x == "PRIMARY") $def .= "   PRIMARY KEY (" . implode($columns, ", ") . ")";
          else if (substr($x,0,6) == "UNIQUE") $def .= "   UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")";
          else if (substr($x,0,8) == "FULLTEXT") $def .= "   FULLTEXT KEY ".substr($x,9)." (" . implode($columns, ", ") . ")";
          else $def .= "   KEY $x (" . implode($columns, ", ") . ")";
     }

     $def .= "\n) TYPE=MyISAM;";
     return (stripslashes($def));
}


function do_backup($_dbhost, $_database)
{


  global $TABLE_PREFIX, $language;

  $drop_table = get_backup_settings("backup_add_drop_table");
  $add_structure = get_backup_settings("backup_add_structure");
  $add_data = get_backup_settings("backup_add_data");
  $backup_folder = get_backup_settings("backup_folder");

  if ($backup_folder=='')
     $backup_folder=realpath("backup");

  // data array
  $key = array("PRI"=>"PRIMARY KEY","UNI"=>"UNIQUE KEY","MUL"=>"KEY",""=>"");
  $arr = array(); // stucture array

  // do not delete
  $sql_version=mysql_fetch_row(do_sqlquery("SELECT VERSION()"));
  $querys[] = "-- Generated By xbtit\n";
  $querys[] = "-- MySql Dump\n";
  $querys[] = "-- Version: 1.0\n";
  $querys[] = "-- \n";
  $querys[] = "-- Host: ".$_dbhost."\n";
  $querys[] = "-- Server version: ".$sql_version[0]."\n";
  $querys[] = "-- PHP version: ".phpversion()."\n";
  $querys[] = "-- Database: ".$_database."\n";
  $querys[] = "-- \n";
  $querys[] = "-- \n";
  $querys[] = "USE `".$_database."`;\n";
  $querys[] = "-- Rest \n\n";

  // getting tables
  $get_tab = mysql_query("SHOW TABLES FROM `".$_database."`");
  // while tab
  while($x = mysql_fetch_row($get_tab))
  {
    
      // structure vars
      if ($add_structure == 'true')
         {
         $var = get_def($x[0],$drop_table);
         // structure in file
         $querys[] = "\n-- -------------------------------------------------------\n\n";
         $querys[] = $var;
         $querys[] = "\n";
      }
      if ($add_data == 'true')
         {
         $var = get_data($x[0]);
         // structure in file
         $querys[] = "\n";
         $querys[] = $var;
         $querys[] = "\n";
      } // data
  } // large while, tables

  // file handling
  $dat = '';

  $bktime=time();
  // open
  if (function_exists("gzencode"))
     $bkp_file = $backup_folder .'/' . $_database.'-'.date("Y-m-d-H-i-s",$bktime).'.sql.gz';
  else
     $bkp_file = $backup_folder .'/' . $_database.'-'.date("Y-m-d-H-i-s",$bktime).'.sql';

     

  $fp = @fopen($bkp_file,'w');
      // unable to open file
      if(!$fp) {
          return array('result'=>1,'error'=>$language["DB_CANT_OPEN_SQL_FILE"]);
          //stderr($language["ERROR"], );
          //die;
      }
      // charge in var
          foreach($querys as $content) {
          $dat .= $content;
          }
      // write
      if (function_exists("gzencode"))
         $dat=gzencode($dat,9);
      $write = fwrite($fp,$dat);
      // when writing failes
      if(!$write) {
          return array('result'=>2,'error'=>$language["DB_CANT_WRITE_SQL_FILE"]);
          //stderr($language["ERROR"], $language["DB_CANT_WRITE_SQL_FILE"]);
          //die;
      }
  // close
  fclose($fp);

  do_sqlquery("UPDATE `{$TABLE_PREFIX}tasks` SET `last_time` = ".($bktime)." WHERE `task` = 'backup';");

  return array('result'=>0,'error'=>$bkp_file);

}

?>